package com.baba.emq.controller;

import cn.hutool.json.JSONObject;
import com.baba.emq.bean.PublishBean;
import com.baba.emq.handler.MessageHandler;
import com.baba.emq.handler.PublishHandler;
import com.baba.emq.handler.SubscribeHandler;
import com.baba.emq.sdkcore.ServerMqttClient;
import com.baba.emq.utils.JsonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author wulongbo
 * @version 1.0
 * @date 2020/6/4 15:11
 * @description
 */

@RequestMapping("/EMQ")
@Api(tags = "EMQ接口模块")
@RestController
public class EmqController {

//    private static Logger logger = LoggerFactory.getLogger(EmqController.class);

    private String IMEI;

    private String cBackTopic;

    @Autowired
    private PublishBean publishBean;

    @Autowired
    private ServerMqttClient serverMqttClient;

    /**
     * EMQ消息发布订阅
     * @Author wulongbo
     * @CreateTime 2020/5/29 16:34
     */
    @ApiOperation(value="EMQ连接", notes="EMQ连接")
    @RequestMapping("/emqConnection")
    public void emqConnection(){
        serverMqttClient.connect(new MessageHandler() {

            //收到消息
            public void messageArrived(JSONObject receivedMessage) {

                System.out.println("receivedMessage:"+receivedMessage);
//                logger.debug("receivedMessage:"+receivedMessage);

                String topic=receivedMessage.get("topic").toString();

                String payload=receivedMessage.get("payload").toString();

                String firstKey=JsonUtil.getFirstKey(JsonUtil.strToJson(payload));

                System.out.println("firstKey:" + firstKey);
                if(firstKey.equals("register")){
                    //获取对应的值
                    String value= JsonUtil.strToJson(payload).get(firstKey).toString();
                    //把对应的值转成JSONObject数组
                    List<com.alibaba.fastjson.JSONObject> list= JsonUtil.getList(value);
                    //作为参数转换成相应的实体bean 操作
                    System.out.println("作为参数转换成相应的实体bean 操作-----------------success");
                }


                if(topic.startsWith(publishBean.getTOPIC_PREFIX_DEVICE())){

                    //从topic 获取device 的 IMEI
                    IMEI = topic.substring( topic.indexOf("device/") + 7 , topic.lastIndexOf("/client") );

                    //获取 发送给 指定IMEI 的device的topic
                    cBackTopic = publishBean.getDevicePublishTopic(IMEI);

//                    logger.debug("IMEI:"+IMEI+",cBackTopic:"+ cBackTopic);

                    //要发送消息的内容

                    /**
                     * 发布JSON

                     */
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("IMEI", IMEI);
                    jsonObject.put("msgid", System.currentTimeMillis());
                    jsonObject.put("topic", cBackTopic);
                    jsonObject.put("type", "监狱手环");
                    jsonObject.put("price", "100");
                    serverMqttClient.publishJson(cBackTopic, jsonObject, new PublishHandler() {
                        @Override
                        public void onSuccess() {
                            System.out.println("发布消息：topic，成功"+cBackTopic);
//                            logger.debug("JSONObject消息发布成功=====================");
                        }

                        @Override
                        public void onException(Exception e) {
                            System.out.println("发布消息：topic，失败"+cBackTopic);
//                            logger.debug("JSONObject消息发布失败=====================");
                        }
                    });

                }
            }

            //出错
            public void onError(Throwable throwable) {
//                logger.debug("出错=================");
            }

            //发送完成
            public void onComplete(IMqttDeliveryToken iMqttDeliveryToken) {
//                logger.debug("发送完成==============");
            }

            //连接成功
            public void onConnected() {
//                logger.debug("连接成功==============");
            }

        });

        /**
         * 判断是否在线
         */
        if (serverMqttClient.isConnected()) {


            /**
             * 订阅
             */
            serverMqttClient.subscribe(publishBean.getTopic(), 2, new SubscribeHandler() {
                @Override
                public void onSuccess(String topic, int qos) {

                }

                @Override
                public void onError(Exception e) {
//                    logger.debug("订阅失败======================");
                }
            });
        } else {
            System.out.println("连接失败");
//            logger.debug("连接失败");
        }

    }

}
